package com.blb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.config.MyTransactional;
import com.blb.mapper.AccountMapper;
import com.blb.pojo.Account;
import com.blb.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    //事务管理器
//    @Autowired
//    private DataSourceTransactionManager transactionManager;

    /**
     * 转账
     */
    // 思考题：@Transactional的实现原理，我们能否自己实现？
    // 自定义注解 + AOP + 环绕通知 + transactionManager
//    @MyTransactional
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public void transfer(String from, String to, Long money) {
        //启动事务
//        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        Account fromAccount = accountMapper.selectOne(new QueryWrapper<Account>().lambda().eq(Account::getName, from));
        if(fromAccount == null){
            throw new RuntimeException(from + "账号不存在");
        }
        Account toAccount = accountMapper.selectOne(new QueryWrapper<Account>().lambda().eq(Account::getName, to));
        if(toAccount == null){
            throw new RuntimeException(to + "账号不存在");
        }
        //判断from账号余额是否大于money，否则抛异常
        if(fromAccount.getBalance() < money){
            throw new RuntimeException(from + "余额不足");
        }
        //更新from账号余额
        fromAccount.setBalance(fromAccount.getBalance() - money);
        accountMapper.updateById(fromAccount);
//        int x = 10 / 0;
        //更新to账号余额
        toAccount.setBalance(toAccount.getBalance() + money);
        accountMapper.updateById(toAccount);
        //提交事务,如果执行不到这行，中间的数据库操作会回滚
//        transactionManager.commit(status);
    }
}
